﻿namespace WebPacker.Tests.Packs.Watchers
{
	using System;
	using System.IO;
	using System.Linq;
	using System.Threading;
	using NUnit.Framework;
	using WebPacker.Packs.Resources;
	using WebPacker.Packs.Watchers;

	[TestFixture]
	public class WildcardFileWatcherTest : ResourceWatcherBaseTest
	{
		private readonly string testPath;
		private readonly string[] testFiles;

		public WildcardFileWatcherTest()
		{
			testPath = TestHelper.GetSampleFolder("wildcard.watcher");
			testFiles = TestHelper.PrepareSampleFiles(new string[] { "test1.js", "test2.js", "style1.css" }, "wildcard.watcher");
		}

		[Test]
		public void ChangedTest()
		{
			Exception exception = null;
			var changed = false;

			var testCss = Path.Combine(testPath, "tempfile.css");

			if (File.Exists(testCss))
			{
				File.Delete(testCss);
			}

			using (var monitor = new WildcardFileWatcher())
			{
				monitor.NotifyDelay = 10;

				var resource = new WildcardFileResource(testPath + "/*.css");

				monitor.Changed += (sender, ea) =>
				{
					try
					{
						Assert.IsNotNull(sender);
						Assert.AreEqual(resource.Name, ea.ResourceName);
						Assert.AreEqual(1, ea.Resources.Count());
						changed = true;
					}
					catch (Exception e)
					{
						exception = e;
					}
				};

				monitor.Add(resource);

				File.WriteAllText(testCss, "body { border:0 }");
				Thread.Sleep(500);
			}

			if (exception != null)
			{
				throw exception;
			}

			Assert.IsTrue(changed);
		}

		protected override IResourceWatcher GetMonitor()
		{
			return new WildcardFileWatcher();
		}

		protected override IResource GetTestResource()
		{
			return new WildcardFileResource(testPath + "/*.js");
		}

		protected override IResource[] GetTestResources()
		{
			return new IResource[]
			{
				new WildcardFileResource(testPath + "/*.js"),
				new WildcardFileResource(testPath + "/*.css")
			};
		}

		protected override IResource GetNotAcceptableResource()
		{
			return new ContentResource("test", "hoho");
		}
	}
}
